package io.gitee.mingbaobaba.apijson.querycondition.query.template.support;

import io.gitee.mingbaobaba.apijson.querycondition.query.conditions.ApiJsonPageInfo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>循环查询执行器</p>
 */
public class LoopQueryExecutor {

    public <T> List<T> execute(LoopQueryConfig config, PageFetcher<T> fetcher) {
        Objects.requireNonNull(config, "LoopQueryConfig不能为空");
        Objects.requireNonNull(fetcher, "PageFetcher不能为空");
        List<T> result = new ArrayList<>();
        int page = config.getStartPage();
        int limit = config.getLimit();
        long maxRetCount = config.getMaxRetCount();
        boolean continueFetch = true;
        while (continueFetch) {
            ApiJsonPageInfo<T> pageInfo = fetcher.fetch(page, limit);
            if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getData())) {
                break;
            }
            for (T item : pageInfo.getData()) {
                if (result.size() >= maxRetCount) {
                    return result;
                }
                result.add(item);
            }
            continueFetch = needNextPage(pageInfo, page, limit);
            page++;
        }
        return result;
    }

    private <T> boolean needNextPage(ApiJsonPageInfo<T> pageInfo, int page, int limit) {
        Long total = pageInfo.getTotal();
        if (total == null || total <= 0) {
            return !CollectionUtils.isEmpty(pageInfo.getData()) && pageInfo.getData().size() == limit;
        }
        return (long) page * limit < total;
    }
}

